package auth

import auth.User
import org.jsecurity.authc.AuthenticationException
import org.jsecurity.authc.UsernamePasswordToken
import org.apache.commons.codec.digest.DigestUtils
import org.jsecurity.SecurityUtils

class UserController {
    def jsecSecurityManager

    def index = { redirect(action: 'login', params: params) }

    def register = {
        def renderParams = [model:[originalURI:params.originalURI, formData:params, async:request.xhr]]

        if (request.xhr)
            renderParams.template = "registerForm"
        else
            renderParams.view = "register"

        if (request.method == 'POST') {
            def user = User.findByEmail(params.email)
            if (user) {
                renderParams.model.message = "auth.user.already.exists"
                render(renderParams)
            } else {
                if (params.password != params.password2) {
                    renderParams.model.message = "auth.password.mismatch"
                    render(renderParams)
                } else {
                    user = new User(email:params.email, password:(params.password?DigestUtils.shaHex(params.password):null))
                    if (!user.hasErrors() && user.save(flush:true)) {
                        // One can create meta information and add them to the User
                        //def userInfo = new UserInfo(params)
                        //userInfo.user = user
                        //userInfo.save()
                        println "Will call UsernamePasswordToken for ${user.email} and ${user.password}"

                        def authToken = new UsernamePasswordToken(user.email, params.password)
                        this.jsecSecurityManager.login(authToken)

                        if (params.originalURI) {
                            redirect(url:params.originalURI, params:params)
                        } else {
                            redirect(uri:"")
                        }
                    } else {
                        renderParams.model.user = user
                        render(renderParams)
                    }
                }
            }
        } else {
            render(renderParams)
        }
    }

    def login = {
        if (request.method == 'POST') {
            println "Try to authentivcate as ${params.email} with ${params.password}"
            def authToken = new UsernamePasswordToken(params.email, params.password)
            println authToken

            // Support for "remember me"
            if (params.rememberMe) {
                authToken.rememberMe = true
            }

            try{
                // Perform the actual login. An AuthenticationException
                // will be thrown if the username is unrecognised or the
                // password is incorrect.
                this.jsecSecurityManager.login(authToken)

                // If a controller redirected to this page, redirect back
                // to it. Otherwise redirect to the root URI.
                def targetUri = params.targetUri ?: "/"

                log.info "Redirecting to '${targetUri}'."
                redirect(uri: targetUri)
            } catch (AuthenticationException ex){
                if (request.xhr) {
                    render(template:"loginForm", model:[originalURI:params.originalURI,
                                                        formData:params,
                                                        async:true,
                                                        message:"auth.invalid.login"])
                } else {
                    flash.message = "Invalid username and/or password"
                    redirect(action:'login', params:[username:params.email])
                }
            }
        } else {
            render(view:"login")
        }
    }

    def logout = {
        // Log the user out of the application.
        SecurityUtils.subject?.logout()
        // For now, redirect back to the home page.
        redirect(uri: '/')
    }

    def unauthorized = {
        render 'You do not have permission to access this page.'
    }
}
    